<template>
  <el-dialog
    v-model="visible"
    :title="scheduleDetail?.title || '日程详情'"
    :width="dialogWidth"
    :class="{ 'mobile-dialog': isMobile }"
    @close="handleClose"
  >
    <div v-if="loading" class="loading">
      <el-skeleton :rows="8" animated />
    </div>
    
    <div v-else-if="scheduleDetail" class="schedule-detail">
      <div class="detail-section">
        <div class="detail-header">
          <div class="detail-title">基本信息</div>
        </div>
        
        <el-descriptions :column="isMobile ? 1 : 2" border>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(scheduleDetail.status)">
              {{ getStatusLabel(scheduleDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(scheduleDetail.priority)">
              {{ getPriorityLabel(scheduleDetail.priority) }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item label="开始时间">
            {{ formatDateTime(scheduleDetail.start_time) }}
          </el-descriptions-item>
          
          <el-descriptions-item label="结束时间">
            {{ formatDateTime(scheduleDetail.end_time) }}
          </el-descriptions-item>
          
          <el-descriptions-item label="负责人">
            {{ scheduleDetail.member_name }}
          </el-descriptions-item>
          
          <el-descriptions-item label="重复类型">
            {{ getRepeatLabel(scheduleDetail.repeat_type) }}
          </el-descriptions-item>
          
          <el-descriptions-item v-if="scheduleDetail.repeat_until" label="重复截止">
            {{ formatDateTime(scheduleDetail.repeat_until) }}
          </el-descriptions-item>
          
          <el-descriptions-item v-if="scheduleDetail.location" label="位置" :span="2">
            {{ scheduleDetail.location }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-if="scheduleDetail.description" class="detail-section">
        <div class="detail-header">
          <div class="detail-title">描述</div>
        </div>
        <div class="detail-content">
          {{ scheduleDetail.description }}
        </div>
      </div>

      <div v-if="scheduleDetail.is_reminder_enabled" class="detail-section">
        <div class="detail-header">
          <div class="detail-title">提醒设置</div>
        </div>
        <el-descriptions :column="isMobile ? 1 : 2" border>
          <el-descriptions-item label="提醒状态">
            <el-tag type="success">已启用</el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item v-if="scheduleDetail.reminder_minutes" label="提醒时间">
            提前 {{ scheduleDetail.reminder_minutes }} 分钟
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-if="scheduleDetail.participants && scheduleDetail.participants.length > 0" class="detail-section">
        <div class="detail-header">
          <div class="detail-title">参与者</div>
        </div>
        <div class="participants-list">
          <div v-for="participant in scheduleDetail.participants" :key="participant.id" class="participant-item">
            <div class="participant-info">
              <div class="participant-name">{{ participant.member_name }}</div>
              <div class="participant-status">
                <el-tag 
                  :type="participant.has_confirmed ? 'success' : 'warning'"
                  size="small"
                >
                  {{ participant.has_confirmed ? '已确认' : '待确认' }}
                </el-tag>
                <el-tag v-if="participant.is_required" type="info" size="small">
                  必需
                </el-tag>
              </div>
            </div>
            <div v-if="participant.confirmed_at" class="participant-time">
              确认时间: {{ formatDateTime(participant.confirmed_at) }}
            </div>
            <div v-if="participant.notes" class="participant-notes">
              备注: {{ participant.notes }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="scheduleDetail.notes" class="detail-section">
        <div class="detail-header">
          <div class="detail-title">备注</div>
        </div>
        <div class="detail-content">
          {{ scheduleDetail.notes }}
        </div>
      </div>

      <div class="detail-section">
        <div class="detail-header">
          <div class="detail-title">其他信息</div>
        </div>
        <el-descriptions :column="isMobile ? 1 : 2" border>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(scheduleDetail.created_at) }}
          </el-descriptions-item>
          
          <el-descriptions-item v-if="scheduleDetail.updated_at" label="更新时间">
            {{ formatDateTime(scheduleDetail.updated_at) }}
          </el-descriptions-item>
          
          <el-descriptions-item label="家庭">
            {{ scheduleDetail.family_name }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useScheduleStore } from '@/stores/schedule';
import { useScreenSize } from '@/utils/responsive';
import { ScheduleStatus, SchedulePriority, ScheduleRepeatType } from '@/types/schedule';

interface Props {
  visible: boolean;
  scheduleId: number | null;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'edit', id: number): void;
  (e: 'delete'): void;
  (e: 'refresh'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const scheduleStore = useScheduleStore();
const { isMobile, dialogWidth } = useScreenSize();

const loading = ref(false);

const scheduleDetail = computed(() => scheduleStore.currentSchedule);

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const loadScheduleDetail = async () => {
  if (!props.scheduleId) return;
  
  try {
    loading.value = true;
    await scheduleStore.fetchScheduleById(props.scheduleId);
    await scheduleStore.fetchScheduleParticipants(props.scheduleId);
  } catch (error) {
    console.error('Load schedule detail error:', error);
  } finally {
    loading.value = false;
  }
};

const formatDateTime = (datetime: string) => {
  return new Date(datetime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

const getStatusTagType = (status: ScheduleStatus) => {
  switch (status) {
    case ScheduleStatus.COMPLETED: return 'success';
    case ScheduleStatus.IN_PROGRESS: return 'primary';
    case ScheduleStatus.PENDING: return 'warning';
    case ScheduleStatus.CANCELLED: return 'info';
    default: return 'info';
  }
};

const getStatusLabel = (status: ScheduleStatus) => {
  switch (status) {
    case ScheduleStatus.COMPLETED: return '已完成';
    case ScheduleStatus.IN_PROGRESS: return '进行中';
    case ScheduleStatus.PENDING: return '待处理';
    case ScheduleStatus.CANCELLED: return '已取消';
    default: return '未知';
  }
};

const getPriorityTagType = (priority: SchedulePriority) => {
  switch (priority) {
    case SchedulePriority.URGENT: return 'danger';
    case SchedulePriority.HIGH: return 'warning';
    case SchedulePriority.MEDIUM: return 'primary';
    case SchedulePriority.LOW: return 'info';
    default: return 'info';
  }
};

const getPriorityLabel = (priority: SchedulePriority) => {
  switch (priority) {
    case SchedulePriority.URGENT: return '紧急';
    case SchedulePriority.HIGH: return '高';
    case SchedulePriority.MEDIUM: return '中';
    case SchedulePriority.LOW: return '低';
    default: return '未知';
  }
};

const getRepeatLabel = (repeatType: ScheduleRepeatType) => {
  switch (repeatType) {
    case ScheduleRepeatType.DAILY: return '每天';
    case ScheduleRepeatType.WEEKLY: return '每周';
    case ScheduleRepeatType.MONTHLY: return '每月';
    case ScheduleRepeatType.YEARLY: return '每年';
    case ScheduleRepeatType.NONE: return '不重复';
    default: return '未知';
  }
};

const handleClose = () => {
  visible.value = false;
  scheduleStore.clearCurrentSchedule();
};

const handleEdit = () => {
  if (props.scheduleId) {
    emit('edit', props.scheduleId);
  }
};

const handleDelete = async () => {
  if (!props.scheduleId) return;
  
  try {
    await ElMessageBox.confirm(
      '确定要删除这个日程吗？此操作不可恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await scheduleStore.deleteSchedule(props.scheduleId);
    emit('delete');
    handleClose();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete schedule error:', error);
    }
  }
};

watch(() => props.visible, (newValue) => {
  if (newValue && props.scheduleId) {
    loadScheduleDetail();
  }
});
</script>

<style lang="scss" scoped>
.loading {
  padding: 20px;
}

.schedule-detail {
  .detail-section {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-border-color-light);
  }
  
  .detail-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .detail-content {
    line-height: 1.6;
    color: var(--el-text-color-regular);
    padding: 12px;
    background: var(--el-bg-color);
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color-lighter);
  }
}

.participants-list {
  .participant-item {
    padding: 12px;
    margin-bottom: 8px;
    background: var(--el-bg-color);
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color-lighter);
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .participant-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .participant-name {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
  
  .participant-status {
    display: flex;
    gap: 8px;
  }
  
  .participant-time,
  .participant-notes {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.mobile-dialog) {
  .el-dialog {
    margin: 0 !important;
    margin-top: 10px !important;
    border-radius: var(--el-border-radius-small);
  }
  
  .el-dialog__body {
    padding: 16px;
  }
}
</style>